<?php 
namespace frontend\frontBundle\Security\User;

use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;

use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;

use frontend\frontBundle\Exception\LoginErroException;

class WebserviceUserProvider implements UserProviderInterface
{
	private $container;
	
	public function __construct(Container $container){
    	$this->container = $container;
  	}
	
  	public function loadUserByUsername($username)
    {
        $session = $this->container->get('session');
    	$em      = $this->container->get('doctrine')->getEntityManager();
		//
        $username = $this->container->get('request')->get("_username");
    	$password = $this->container->get('request')->get("_password");
    	$salt = '';
    	$roles = array('ROLE_ADMIN');
		//==================== Check Info User On Database ========================================================
    	$userInfo = $em->getRepository('frontendfrontBundle:Users')->getUserInfo($username, md5($password));
		if(count($userInfo) <= 0) throw new LoginErroException(sprintf('USER_LOGIN_ERR_0001'));
		
		$userData = array("username"=>$username, "password"=>$password, "salt"=>$salt, "roles"=>$roles);	
		//==================== Check Info User On Database ========================================================
		if($userData){
			$session->set("AnphunongUserInfo", $userData);
			return new WebserviceUser($username, $password, $salt, $roles);
        }
        throw new LoginErroException(sprintf('USER_LOGIN_ERR_0001'));
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof WebserviceUser) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
        }
		$session = $this->container->get('session');
    	$data = $session->get("AnphunongUserInfo");
		
		return new WebserviceUser($data['username'], $data['password'], $data['salt'], $data['roles']);
        //return $this->loadUserByUsername($user->getUsername());
    }

    public function supportsClass($class)
    {
        return $class === 'frontend\frontBundle\Security\User\WebserviceUser';
    }
}
?>